import Vue from 'vue'
import Component from 'vue-class-component'
import {readFile, uploadImages} from '@/utils/uploadImage/index'
import './productStyle.css'
import { Indicator } from 'mint-ui'
import {Toast} from 'mint-ui'
import Platform from '@/supports/platform'

@Component
export default class ProductEditClass extends Vue {
  selected = '0'

  product = {}

  productId = ''
  // 自己创建

  isLoadCover = false
  isLoadImages = false
  productDesc = ''
  isGetDetail = false
  type = ''
  maxImage = 9

  created() {
    this.wrapperHeight = document.documentElement.clientHeight - 112
    eventBus.$on('productEditLoadImages', this.handleProductEditLoadImages)
  }

  activated () {
    this.product = {}
    this.productId = this.$route.params.productId
    if (this.$store.getters.productEdit.productCover) {
      this.initProduct()
    } else {
      this.getDetail()
    }
  }

  destroyed () {
    this.$store.commit('setProductEdit', this.product)
  }

  handlePop () {
    this.product = {}
    this.$router.go(-1)
  }

  initProduct() {
    if (this.$store.getters.productEdit) {
      this.product = this.$store.getters.productEdit
      this.product.productDesc = this.$store.getters.productEdit.productDesc
      console.log('product')
      console.log(this.product)
    }
  }

  updated () {
    if (this.$route.query.temp) {
      this.product.designerName = this.$route.query.temp.name
    }
  }

  async getDetail () {
    let url = '/buyer/v1/product/'

    try {
      const response = await this.$axios.post(url + this.productId, {})
      if (response.status === 0) {
        this.product = response.data
        this.product['code'] = response.data.code
        this.product.imagesFiles = response.data.imageUrls
        let desc = response.data.description ? response.data.description : []
        this.product.productDesc = desc.join('\n')
        // this.product.productDesc = desc
        if (this.product.skus) {
          let sku = this.product.skus[0]
          if (sku.xsizes) {
            let size = sku.xsizes[0]
            console.log('skuImages')
            console.log(size.skuImages)
            console.log(sku.xsizes)

            this.product.newSkus = []
            for (let obj of sku.xsizes) {
              console.log(obj)
              let size = obj.size ? obj.size : ''
              let count = obj.productSkuQuantity ? obj.productSkuQuantity : 0
              let dic = {showPrice: obj.showPrice, size: size, productSkuQuantity: count, description: desc, productSkuId: obj.productSkuId}
              this.product.newSkus.push(dic)
            }
            console.log('123434')
            console.log(this.product.newSkus)
          }
        }
      }
    } catch (e) {
      console.log(e)
    }
  }

  async addRequest () {
    try {
      if (this.product.code && this.product.code.length > 6) {
        Toast('编码大于6位')
        return
      }
      if (!this.product.productCover || this.product.productCover.length <= 0) {
        Toast('没有封面图')
        return
      }
      if (!this.product.designerName) {
        Toast('请输入品牌')
        return
      }
      if (this.product.productName.length <= 0) {
        Toast('请输入商品名')
        return
      }
      if (this.product.imagesFiles.length <= 0) {
        Toast('没有商品图片')
        return
      }
      if (this.product.newSkus.length <= 0) {
        Toast('没有SKU')
        return
      }
      if (!this.hadSize()) {
        Toast('size不能为空')
        return
      }
      let descs = this.product.productDesc.split(/[\n]/g)
      let params = {
        productId: this.productId,
        code: this.product.code.length > 6 ? this.product.code.substring(0, 6) : this.product.code,
        productCover: this.product.productCover,
        description: descs,
        designerName: this.product.designerName,
        imageUrls: this.product.imagesFiles,
        productName: this.product.productName,
        skus: [{xsizes: this.product.newSkus}],
        sourceType: 0
      }
      Indicator.open()

      const response = await this.$axios.post('/buyer/v1/product/modify', params)
      if (response.status === 0) {
        // this.filterItems = response.data
        // for (let obj of this.filterItems) {
        //   if (obj.name === '品牌') {
        //     this.$store.commit('setAllBrands', obj.children)
        //   }
        // }
        this.handlePop()
      }
      Indicator.close()
    } catch (e) {
      Indicator.close()

      console.log(e)
    }
  }

  hadSize () {
    for (var i = 0; i < this.product.newSkus.length; i++) {
      let dic = this.product.newSkus[i]
      if (!dic.size || dic.size.length <= 0) {
        return false
      } else {
        return true
      }
    }
  }

  get caculateHeight() {
    return 'height:' + String(this.wrapperHeight) + 'px'
  }

  // 删除SKU
  handlerDeleteSku (index) {
    this.product.newSkus.splice(index, 1)
    this.strongUpdate()
  }

  handlerAddSku () {
    if (!this.product.newSkus) {
      this.product.newSkus = []
    }
    this.product.newSkus.push({showPrice: '', size: '', productSkuQuantity: '', description: ''})
    this.strongUpdate()
  }

  // 输入的size是否存在
  handleCheckSize (size, value) {
    for (var i = 0; i < this.product.newSkus.length; i++) {
      let dic = this.product.newSkus[i]
      if (size === dic.size) {
        this.product.skus.splice(i, 1)
        // MessageBox.confirm('尺码已存在', '')
        alert('尺码已存在')
        return
      }
    }
    value.size = size
  }

  handleFiles(e) {
    this.type = e.target.id
    if (this.type === 'coverFileElem') {
      Platform.choosePhotos('1', 'productEditLoadImages')
    } else {
      Platform.choosePhotos('2', 'productEditLoadImages')
    }
  }

  handleProductEditLoadImages(images) {
    if (images && images.length > 0) {
      if (this.type === 'formImagesFile') {
        this.product.imagesFiles = this.product.imagesFiles.concat(images)
      } else if (this.type === 'coverFileElem') {
        this.product.productCover = images[0]
      }
      this.strongUpdate()
    }
  }

  handleDeleteImage (index) {
    this.product.imagesFiles.splice(index, 1)
    this.strongUpdate()
  }

  strongUpdate() {
    let cover = this.product.productCover
    this.product.productCover = ''
    this.product.productCover = cover
  }
  handleDeleteCoverImage (index) {
    this.product.productCover = ''
  }

  createImageItem() {
    if (!this.product.imagesFiles) {
      return
    }
    const item = this.product.imagesFiles.map((image, index) => {
      return <span>
      <dd class='productDeleteImageClass' onClick={() => this.handleDeleteImage(index)}><icon name='imageDeleteIcon' scale='2'/></dd>
      <img src={image + '?x-oss-process=image/resize,m_pad,h_100,w_100,color_ffffff/quality,Q_80/format,jpg'}/>
      </span>
    })
    return item
  }

  // 自己创建商品
  createCustomProduct () {
    return <div style='margin-top:64px'>
      <div class="productAddInput">
        <ul>
          <li class="productAddImage">
            <span>图片</span>
            <div class="productAddImageList">
              {this.createImageItem()}
              <font id="formImagesFile" onClick={this.handleFiles} v-show={!this.product.imagesFiles || this.product.imagesFiles.length <= this.maxImage}>
                <icon id="formImagesFile" name="addIcon" scale='3'/>
              </font>
            </div>
          </li>

          <li class="productAddImage">
            <span>封面</span>
            <div class="productAddImageList">
              <span v-show = {this.product.productCover && this.product.productCover.length > 0}>
                <dd class='productDeleteImageClass' onClick={this.handleDeleteCoverImage}><icon name='imageDeleteIcon' scale='2'/></dd>
                <img src={this.product.productCover + '?x-oss-process=image/resize,m_pad,h_100,w_100,color_ffffff/quality,Q_80/format,jpg'}/>
              </span>
              <font id="coverFileElem" onClick ={this.handleFiles} v-show={!this.product.productCover || this.product.productCover.length === 0 }>
                <icon id="coverFileElem" name="addIcon" scale='3'/>
              </font>
            </div>

          </li>
          <li>
            <span>名称</span>
            <input type="text" placeholder="请输入名称" v-model={this.product.productName}/>
          </li>
          <li onClick={() => { this.$router.push({name: 'brandSelect'}) }}>
            <span>品牌</span>
            <input type="text" placeholder="请选择品牌" value={this.product.designerName ? this.product.designerName : ''} disabled="disabled"/>
            <icon name="rightArrow" class="rightArrow" scale='1.2'/>
          </li>
          <li>
            <span>编码</span>
            <input type="text" placeholder="(1～6位字母加数字)" v-model={this.product.code}/>
          </li>
          <li>
            <span>描述</span>
            <textarea placeholder="输入商品描述" v-model={this.product.productDesc}></textarea>
          </li>
        </ul>
      </div>
      <div class='productFromSkuList'>
        <table cellspacing='0'>
          <thead>
          <tr>
            <td width='40'>SKU</td>
            <td>价格</td>
            <td>尺码</td>
            <td>库存</td>
            <td width='40'><span onClick={this.handlerAddSku}><icon name='addIcon' scale='2.5'/></span></td>
          </tr>
          </thead>
          <tbody>
          {this.createSkuTable()}
          </tbody>
        </table>
      </div>
    </div>
  }

  createSkuTable() {
    if (!this.product.newSkus) {
      return
    }
    const item = this.product.newSkus.map((value, index) => {
      return <tr>
          <td width='40'>
            {index + 1}
          </td>
          <td>
            <input type="text" placeholder="￥" v-model={value.showPrice}/>
          </td>
          <td>
            <input type="text" placeholder="尺码" v-model={value.size}/>
          </td>
          <td>
            <input type="text" placeholder="库存" v-model={value.productSkuQuantity}/>
          </td>
          <td width='40' onClick={() => this.handlerDeleteSku(index)}>
            <icon name='deleteIcon' scale='2'/>
          </td>
        </tr>
    })
    return item
  }

  render () {
    return (
      <div class='content'>
        <mt-header class='header' fixed title="商品编辑">
        <mt-button onClick={this.handlePop} icon="" slot="left"><icon name = 'backIcon' scale='2'/></mt-button>
        <mt-button onClick={this.addRequest} icon="" slot="right"><icon name = 'completeIcon' scale='2'/></mt-button>
        </mt-header>

            {this.createCustomProduct()}

      </div>
    )
  }
}
